#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2020 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK

"""
Display basic system information.

Needs psutil (+ dependencies) installed::

  $ sudo apt-get install python-dev
  $ sudo -H pip install psutil
"""
from luma.core.interface.serial import i2c, spi
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
import os
import sys
import time
from datetime import datetime
from pathlib import Path




if os.name != 'posix':
    sys.exit('{} platform not supported'.format(os.name))

from luma.core.render import canvas
from PIL import ImageFont

try:
    import psutil
except ImportError:
    print("The psutil library was not found. Run 'sudo -H pip install psutil' to install it.")
    sys.exit()


# TODO: custom font bitmaps for up/down arrows
# TODO: Load histogram


def get_device(actual_args=None):
    """
    Create device from command-line arguments and return it.
    """
    if actual_args is None:
        actual_args = sys.argv[1:]
    parser = cmdline.create_parser(description='luma.examples arguments')
    args = parser.parse_args(actual_args)

    if args.config:
        # load config from file
        config = cmdline.load_config(args.config)
        args = parser.parse_args(config + actual_args)

    # create device
    try:
        device = cmdline.create_device(args)
        print(display_settings(device, args))
        return device

    except error.Error as e:
        parser.error(e)
        return None

def display_settings(device, args):
    """
    Display a short summary of the settings.

    :rtype: str
    """
    iface = ''
    display_types = cmdline.get_display_types()
    if args.display not in display_types['emulator']:
        iface = 'Interface: {}\n'.format(args.interface)

    lib_name = cmdline.get_library_for_display_type(args.display)
    if lib_name is not None:
        lib_version = cmdline.get_library_version(lib_name)
    else:
        lib_name = lib_version = 'unknown'

    import luma.core
    version = 'luma.{} {} (luma.core {})'.format(
        lib_name, lib_version, luma.core.__version__)

    return 'Version: {}\nDisplay: {}\n{}Dimensions: {} x {}\n{}'.format(
        version, args.display, iface, device.width, device.height, '-' * 60)

def bytes2human(n):
    """
    >>> bytes2human(10000)
    '9K'
    >>> bytes2human(100001221)
    '95M'
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return "%sB" % n


def today_datetime():
    # load average, uptime
    now = datetime.now()
    today_date = now.strftime("%Y-%m-%d  %a")
    today_time = now.strftime("%H:%M:%S")
    return "%s %s" \
        % (today_date, today_time)


def cpu():
    cpu = psutil.cpu_percent(interval=None)
    return "CPU : %.0f%%" \
        % (cpu)


         
def cpu_temp():
    if not hasattr(psutil, "sensors_temperatures"):
        sys.exit("platform not supported")
    temps = psutil.sensors_temperatures()
    if not temps:
        sys.exit("can't read any temperature")
    for name, entries in temps.items():
        for entry in entries:
            return "Temp: %.1f °C" \
            % (entry.current)


def mem_usage():
    usage = psutil.virtual_memory()
    return "Mem: %s /%s %.0f%%" \
        % (bytes2human(usage.available), bytes2human(usage.total), 100 - usage.percent)


def disk_usage(dir):
    usage = psutil.disk_usage(dir)
    return "Disk: %s /%s  %.0f%%" \
        % (bytes2human(usage.free), bytes2human(usage.total), 100 - usage.percent)


def network(iface):
    stat = psutil.net_if_addrs()[iface][0]
    return "IP : %s" % \
           (stat.address)


def stats(device):
    # use custom font
    font_path = str(Path(__file__).resolve().parent.joinpath('fonts', 'arial.ttf'))
    font2 = ImageFont.truetype(font_path, 11)

    with canvas(device) as draw:
        draw.text((0, 0), today_datetime(), font=font2, fill="white")
        draw.text((0, 3), "_______________________", fill="white")
        draw.text((0, 15), cpu(), font=font2, fill="white")      
        draw.text((0+60, 15), cpu_temp(), font=font2, fill="white")      
        draw.text((0, 28), mem_usage(), font=font2, fill="white")
        draw.text((0, 41), disk_usage('/'), font=font2, fill="white")
        draw.text((0, 54), network('wlan0'), font=font2, fill="white")


def main():
    while True:
        stats(device)
        time.sleep(0.05)


if __name__ == "__main__":
    try:
        serial = i2c(port=1, address=0x3C)
        device = ssd1306(serial)
        main()
    except KeyboardInterrupt:
        pass
